using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;

namespace Ribbon
{
	public class RabGroup : Control
	{
		public static readonly DependencyProperty MenuItemsProperty;

		public static readonly DependencyProperty ShowCaptionProperty;

		public static readonly DependencyProperty TextProperty;

		private List<object> _Items = new List<object>();

		private Visibility _TextHide;

		public ObservableCollection<object> MenuItems
		{
			get
			{
				return (ObservableCollection<object>)GetValue(MenuItemsProperty);
			}
			set
			{
				SetValue(MenuItemsProperty, value);
			}
		}

		public Visibility ShowCaption
		{
			get
			{
				return (Visibility)GetValue(ShowCaptionProperty);
			}
			set
			{
				SetValue(ShowCaptionProperty, value);
			}
		}

		public string Text
		{
			get
			{
				return (string)GetValue(TextProperty);
			}
			set
			{
				SetValue(TextProperty, value);
			}
		}

		public List<object> Items
		{
			get
			{
				return _Items;
			}
			set
			{
				_Items = value;
			}
		}

		public Visibility TextHide
		{
			get
			{
				return _TextHide;
			}
			set
			{
				if (value == _TextHide)
				{
					return;
				}
				_TextHide = value;
				foreach (object item in Items)
				{
					RabButton rabButton = item as RabButton;
					if (rabButton != null)
					{
						rabButton.TextHide = value;
					}
				}
			}
		}

		static RabGroup()
		{
			MenuItemsProperty = DependencyProperty.Register("MenuItems", typeof(ObservableCollection<object>), typeof(RabGroup), new PropertyMetadata(null));
			ShowCaptionProperty = DependencyProperty.Register("ShowCaption", typeof(Visibility), typeof(RabGroup), new UIPropertyMetadata(Visibility.Collapsed));
			TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(RabGroup));
			FrameworkElement.DefaultStyleKeyProperty.OverrideMetadata(typeof(RabGroup), new FrameworkPropertyMetadata(typeof(RabGroup)));
		}

		public RabGroup()
		{
			MenuItems = new ObservableCollection<object>();
		}

		public override void OnApplyTemplate()
		{
			base.OnApplyTemplate();
			StackPanel stackPanel = GetTemplateChild("PART_Items") as StackPanel;
			if (stackPanel != null && Items != null)
			{
				foreach (UIElement item in Items)
				{
					stackPanel.Children.Add(item);
				}
			}
			Button button = GetTemplateChild("PART_Menu") as Button;
			if (button != null)
			{
				button.Click += Btn_Click;
			}
		}

		private void Btn_Click(object sender, RoutedEventArgs e)
		{
			ContextMenu contextMenu = new ContextMenu();
			contextMenu.SetResourceReference(Control.FontFamilyProperty, "FontFamilyDefault");
			contextMenu.ItemsSource = MenuItems;
			contextMenu.PlacementTarget = sender as Button;
			contextMenu.IsOpen = true;
		}
	}
}
